import axios from "axios";
/* 引入nprogress */
import {
  Message
} from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import {
  httpUrl,
  authUrl,
  auth
} from "./config";

axios.defaults.timeout = 30000;

Message.duration = 1000;

axios.interceptors.request.use(
  config => {
    let isLogin = config.url.includes("/oauth/token");
    let url = isLogin ? authUrl : httpUrl;
    config.baseURL = url;
    if (!isLogin) config.headers.Authorization = window.sessionStorage.getItem("token");
    NProgress.start();
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    const res = response.data;
    NProgress.done();
    if (res.access_token) {
      return Promise.resolve(res);
    }
    if (res.errorCode == "0") {
      return Promise.resolve(res.bizContent);
    } else if (res.errorCode == "401") {
      Message.error("授权超时,请重新登录");
      window.location.pathname = "/login";
      return Promise.reject(res);
    } else {
      Message.error(res.errorMessage);
      return Promise.reject(res);
    }
  },
  function(err) {
    if (err && err.response) {
      let errCodes = [400, 401, 403, 404, 408];
      let errs = ['请求错误', '授权超时,请重新登录', '拒绝访问', '请求地址不存在', '请求超时'];
      let errInd = errCodes.indexOf(err.response.status);
      let errData = err.response.data.message || err.response.data.error_description;
      err.message = errInd == -1 ? errData : errs[errInd] + err.response.status;
    } else {
      err.message = "连接服务器失败!";
    }
    NProgress.done();
    Message.error(err.message);
    return Promise.reject(err.response.data);
  }
);

export default axios;

//封装get
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  });
}

//封装post
export function post(url, params) {
  let header = url =='/oauth/token' ? {headers: {"Content-Type": "application/x-www-form-urlencoded"},auth}:{};
  return new Promise((resolve, reject) => {
    axios.post(url, params,header).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  });
}
